<template>
  <div class="main-verticalDistanceAnalysis">

  </div>
</template>

<script>
import clearWindow from "@/components/js/clearWindow";
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import jjStandard from "@/components/js/jingjuOptions";
import highLightColor from "@/components/js/highColor";
// eslint-disable-next-line no-unused-vars
let openLayer = null
let selectEntity = [];
// eslint-disable-next-line no-unused-vars
let from = null
// eslint-disable-next-line no-unused-vars
let dataTable = []
// eslint-disable-next-line no-unused-vars
let $table = $('#jj_table');

let dataset = []

let line_hdm = null;
export default {
  name: "verticalDistanceAnalysis",
  components: {},
  data() {
    return {};
  },
  mounted() {
    this.runCommand()
  },
  methods: {
    clearDraw() {
      window.viewer.dadi.draw.clearDraw();
      for (var i = 0; i < selectEntity.length; i++) {
        selectEntity[i].billboard.image = 'img/marker/mark3.png';
      }
      selectEntity = [];
      from = null;
      dataTable = []
    },
    showOpenLayer() {
      if (openLayer) return;
      openLayer = layui.layer.open({
        type: 1,
        area: ['800px', '400px'], // 宽高
        title: "垂直净距分析", // 不显示标题栏
        offset: ['100px', '20px'],
        closeBtn: 1,
        shade: false,
        shadeClose: false, // 点击遮罩关闭层
        content: `<table
                id="jj_table"
                data-toggle="table"
                data-height="200"
                data-width="430"
                data-search="false"
                data-pagination="true"
                style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
                >
                <thead id="jj_thead" style="color:#fff;">

                </thead>
            </table>
            <div style="width:300px;" id="jj-container">

            </div>`,
        // eslint-disable-next-line no-unused-vars
        cancel: (index, layero, that) => {
          this.$emit('quit')
          layer.close(index);
          openLayer = null;
          return false; // 阻止默认关闭行为
        },
        // eslint-disable-next-line no-unused-vars
        success: (layero, index) => {
          $table = $('#jj_table');
        }
      });
    },
    // eslint-disable-next-line no-unused-vars
    updateSelect(drawEntity) {
      // 拿到绘制的geojson
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      if (drawGeojson.features[0].properties.type === 'circle') {
        from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
      } else if (drawGeojson.features[0].properties.type === 'polygon' || drawGeojson.features[0].properties.type === 'polyline') {
        from = turf.feature(drawGeojson.features[0].geometry)
      } else if (drawGeojson.features[0].properties.type === 'rectangle') {
        let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
          a.splice(-1)
          b.splice(-1)
          return a.concat(b)
        })
        from = turf.bboxPolygon(geo)
      }
      let features = [], properties = [];
      let count = 0; // 计数器，计算什么时候执行完毕

      layersMap.forEach(async item => {
        let layer = Object.values(window.viewer.dadi.layers).find(l => l.config.id === item.id)
        if (layer?._visible) {
          const r = await fetchData(item.url)
          // 求交集
          r.features.forEach(fea => {
            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, from);
            if (withIntersect) {
              features.push(fea)
              properties.push(fea.properties)
            }
          })
          count++;
        } else {
          count++;
        }
      })
      let timer = setInterval(() => {
        if (count === layersMap.length) {
          window.clearInterval(timer);
          if (features.length) {
            let thead = `<tr>`
            Object.keys(properties[0]).forEach(key => {
              thead += `<th data-field="${key}">${key}</th>`
            })
            thead += `</tr>`
            $table.bootstrapTable('destroy')
            $('#jj_thead').html(thead)
            dataTable = properties;
            $table.bootstrapTable({
              data: properties.slice(0, 2),
              // eslint-disable-next-line no-unused-vars
              onClickRow: (row, $element) => {
                this.highLight(row)
              }
            })
          }
        }
      }, 1000)
    },
    async highLight(row) {
      let name = row['线型码']
      window.viewer.scene.primitives._primitives.forEach(tileset => {
        if (tileset instanceof Cesium.Cesium3DTileset) {
          tileset.style = new Cesium.Cesium3DTileStyle({
            color: {
              conditions: [
                ["${name} === '" + name + "'", 'color("red", 1)'.replace('red', highLightColor)],
                ['true', 'color("white")']
              ]
            },
          });
        }
      })


      let layer = layersMap.find(l => l.pipelineType === row['管线类型'])
      const res = await fetchData(layer.url)
      const feature = res.features.find(fea => fea.properties['线型码'] === row['线型码'])
      var highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
      if (!highLightLayer) {
        highLightLayer = new Cesium.CustomDataSource('highLightLayer')
        window.viewer.dataSources.add(highLightLayer)
      }
      // 绘制
      highLightLayer.entities.removeAll()
      feature.geometry.coordinates.forEach(coordinate => {

        highLightLayer.entities.add({
          name: "polyline",
          polyline: {
            show: true, //是否显示，默认显示
            positions: Cesium.Cartesian3.fromDegreesArrayHeights([...coordinate.flat()]),
            width: 2, //线的宽度（像素），默认为1
            granularity: Cesium.Math.RADIANS_PER_DEGREE,
            material: Cesium.Color.BLUE.withAlpha(0.99), //线的颜色，默认为白色
            // depthFailMaterial: Cesium.Color.RED, //线被遮挡部分的颜色，默认为空（不显示被遮挡的部分），设置后可显示被遮挡的部分
            arcType: Cesium.ArcType.NONE, //线的地理类型，NONE表示纯直线，GEODESIC表示为测地线，RHUMB表示等角航线，默认为测地线
            // arcType: Cesium.ArcType.GEODESIC,
            // arcType: Cesium.ArcType.RHUMB,
            clampToGround: false, //是否贴地，默认为否
            shadows: Cesium.ShadowMode.DISABLED, //是否显示光照阴影，默认为否
            // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(100.0, 2000000.0), //显示的视角距离条件，在该范围内显示，范围不显示，默认为空
            classificationType: Cesium.ClassificationType.BOTH,
            zIndex: 0, //显示深度，越大表示图层在上
          }
        })
      })
      window.viewer.flyTo(highLightLayer, {
        offset: new Cesium.HeadingPitchRange(0.0, -3.1415926 / 2.0, 70.0),
      })
    },
    rendererHdmChart(dataset) {
      // eslint-disable-next-line no-unused-vars
      let shuipingjuli = dataset[1].shuipingjuli
      let chuizhijianju = dataset[1].chuizhijianju
      let jjItem = jjStandard.find(item => {
        const {type1, type2} = item
        let flag1 = type1.split('、').some(type => {
          return dataset[0]['管线类型'].includes(type)
        })
        let flag2 = type2.split('、').some(type => {
          return dataset[1]['管线类型'].includes(type)
        })
        return flag1 && flag2
      })


      if (!jjItem) {
        alert('没找到规范标准')
        return;
      }

      // 水平距离，是否规范，规范值
      $('#jj-container').html(
          `
                <div style="display:flex;justify-content:space-between;"><label>垂直距离:</label><span>${chuizhijianju}</span></div>
                <div style="display:flex;justify-content:space-between;"><label>规范值:</label><span>${jjItem['限距']}</span></div>
                <div style="display:flex;justify-content:space-between;"><label>是否规范:</label><span>${chuizhijianju >= jjItem['限距'] ? '是' : '否'}</span></div>
            `
      )
    },

    updateSelect_chart() {
      // 拿到绘制的geojson
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      line_hdm = turf.feature(drawGeojson.features[0].geometry)
      dataset = [];
      let count = 0; // 计数器，计算什么时候执行完毕
      layersMap.forEach(async item => {
        let layer = Object.values(window.viewer.dadi.layers).find(l => l.config.id === item.id)
        // console.log(layer)
        if (layer?._visible) {
          const r = await fetchData(item.url)
          // 求交集
          r.features.forEach(fea => {
            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, line_hdm);
            if (withIntersect) {
              const {properties} = fea;
              // 求交点算埋深，水平距离, 垂直距离
              var intersectPoint = turf.lineIntersect(to, line_hdm);
              // console.log(intersectPoint, to);
              let qdms = properties['起点埋深']
              let zdms = properties['终点埋深']
              let qdgc = properties['起点高程']
              let zdgc = properties['终点高程']
              // 算距离和比例
              var fromQd = turf.point(to.geometry.coordinates[0][0].slice(0, -1));
              var fromZd = turf.point(to.geometry.coordinates[0][1].slice(0, -1));
              // var to = turf.point([-75.534, 39.123]);
              var options = {units: 'kilometers'};
              var distance1 = turf.distance(fromQd, (intersectPoint.features)[0], options);
              var distance2 = turf.distance((intersectPoint.features)[0], fromZd, options);
              // console.log(distance1, distance2, distance1 / distance2)

              let currMs = qdms + (zdms - qdms) * (distance1 / distance2) // 相交点埋深
              let currDmgc = qdgc + (zdgc - qdgc) * (distance1 / distance2) // 相交点地面高程
              let currGc = currDmgc - currMs; // 当前管点的高层
              // 水平间距，垂直间距都是相对第一个的
              let chuizhijianju = 0, shuipingjuli = 0;
              if (dataset.length > 0) {
                let number1 = dataset[0];
                chuizhijianju = currGc - number1.guanxiangaocheng;
                shuipingjuli = turf.distance((intersectPoint.features)[0], turf.point(number1.currentCoordianate), options);
              }

              let item = {
                currentCoordianate: (intersectPoint.features)[0].geometry.coordinates,
                guanxianleixing: properties['管线类型'],
                bianhao: properties['管线编码'],
                leixing: properties['材质'],
                guanxiangaocheng: currGc.toFixed(4),
                guanxianguige: properties['管径'],
                chuizhijianju: chuizhijianju,
                dimian: currDmgc.toFixed(4),
                guandiangc: currGc.toFixed(4),
                maisheng: currMs.toFixed(4),
                shuipingjuli: shuipingjuli,
                guanjing: properties['管径'],
                ...properties,
              }
              dataset.push(item)
            }
          })
          count++;
        } else {
          count++;
        }
      })

      let timer = setInterval(() => {
        if (count === layersMap.length) {
          window.clearInterval(timer);
          if (dataset.length < 2) {
            this.$message.warning('请选择两条管线')
            this.$emit('quit')
          } else {
            this.rendererHdmChart(dataset);
          }
        }
      }, 1000)
    },
    runCommand() {
      openLayer = null;
      clearWindow()
      this.clearDraw()

      window.viewer.dadi.draw.startDraw({
        "type": "polyline",
        "style": {
          "lineType": "solid",      //线型
          "animationDuration": 1000,      //速度
          "animationImage": "img/textures/lineClr.png",      //图片
          "color": "#3388ff",      //颜色
          "width": 4,      //线宽
          "clampToGround": false,      //是否贴地
          "outline": false,      //是否衬色
          "outlineColor": "#ffffff",      //衬色颜色
          "outlineWidth": 2,      //衬色宽度
          "opacity": 1,      //透明度
          "zIndex": 0,      //层级顺序
        },
        success: (entity) => {
          this.showOpenLayer();

          this.updateSelect(entity);
          // $('#jj_pickPanel').css('display', $('#jj_pickPanel').css('display') === 'none' ? 'block' : 'bolck');

          this.updateSelect_chart()
        }
      });
    }
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    clearWindow()
    let highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
    if (!highLightLayer) {
      highLightLayer = new Cesium.CustomDataSource('highLightLayer')
      window.viewer.dataSources.add(highLightLayer)
    }
    // 绘制
    highLightLayer.entities.removeAll()
  },
}
</script>

<style scoped>
.main-verticalDistanceAnalysis {
  position: relative;
  height: 0;
  width: 0;
}
</style>
